using System.Linq;
using Shop.Backend.Api.Entity;
using Shop.Backend.Api.Params;
using Shop.Backend.Api.Repository;
using Shop.Backend.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;

namespace Shop.Backend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    //这里的控制器是 Orders 订单
    public class OrdersController : ControllerBase
    {
        private IConfiguration _configuration;
        private IRepository<Users> _usersRepository;
        private IRepository<Goods> _goodsRepository;
        private IRepository<Shops> _shopsRepository;
        private IRepository<Orders> _ordersRepository;
        private IRepository<GoodsCategory3> _goodsCategoryRepository;

        private TokenParameter _tokenParameter;


        public OrdersController(IConfiguration configuration
        , IRepository<Users> usersRepository
        , IRepository<Goods> goodsRepository
        , IRepository<Shops> shopsRepository
        , IRepository<GoodsCategory3> goodsCategoryRepository
        , IRepository<Orders> ordersRepository)
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _goodsRepository = goodsRepository;
            _shopsRepository = shopsRepository;
            _ordersRepository = ordersRepository;
            _goodsCategoryRepository = goodsCategoryRepository;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }


        [HttpGet]
        public dynamic Get([FromQuery] QueryWithPager query)
        {
            // get请求默认从url中获取参数，如果需要使用实体接收参数，需要FromQuery特性
            var pageIndex = query.Pager.PageIndex;
            var pageSize = query.Pager.PageSize;

            var keyword = string.IsNullOrEmpty(query.Keyword) ? "" : query.Keyword.Trim();

            var orders = _ordersRepository.Table.ToList()
            .Where(x => x.IsDeleted == false)
            .Select(a =>
            {
                var goods = _goodsRepository.Table.ToList().Where(y => y.Id == a.FromGoodsId).FirstOrDefault();//拿到商品名字
                var category = _goodsCategoryRepository.Table.ToList().Where(z => z.Id == goods.FromGoodsCategory3Id).FirstOrDefault();//拿到分类名字

                return new 
                {
                    Id = a.Id,
                    GoodsName = goods.GoodsName,
                    PayMoney = a.PayMoney,
                    OrderNumber = a.OrderNumber,
                    FromGoodsCategory = category.CategoryName,
                    GoodsNum = a.GoodsNum,
                    PaymentType = a.PaymentType,
                    IsActived = a.IsActived,
                    CreatedTime = a.CreatedTime,
                    Remarks = a.Remarks
                };
            });

            // 如果keyword不为空，则再去查询用户名
            if (!string.IsNullOrEmpty(keyword))
            {
                orders = orders.Where(x => x.Id.ToString() == keyword
              || x.OrderNumber.Contains(keyword)
              || x.PaymentType.Contains(keyword)); //未完善的模糊查询
            }
            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = new
                {
                    Data = orders,
                    Pager = new
                    {
                        pageIndex,
                        pageSize,
                        rowsTotal = orders.Count()
                    }
                },
                Msg = "获取订单成功^_^"
            });
        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var orders = _ordersRepository.GetById(id);
            return new
            {
                Code = 1000,
                Data = orders,
                Msg = "获取指定订单成功^_^"
            };
        }

        [HttpPost]
        public dynamic Post(CreateOrder createOrder)
        {


            var OrderNo = DateTime.Now.Year.ToString().Substring(2, 2) + DateTime.Now.Month.ToString().PadLeft(2, '0')
                        + DateTime.Now.Day.ToString().PadLeft(2, '0') + DateTime.Now.Hour.ToString().PadLeft(2, '0')
                        + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0')
                        + DateTime.Now.ToString("fff");

            if (string.IsNullOrEmpty(OrderNo))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "订单生成失败"
                };
            }
            var order = new Orders
            {
                OrderNumber = OrderNo,
                PaymentType = createOrder.PaymentType,
                IsPay = createOrder.IsPay,
                FromUsersId = createOrder.FromUsersId,
                FromGoodsExpressAddressId = createOrder.FromGoodsExpressAddressId,
                FromShopsId = createOrder.FromShopsId,
                FromGoodsId = createOrder.FromGoodsId,
                GoodsNum = createOrder.GoodsNum,
                IsDataFlag = createOrder.IsDataFlag,
                PayMoney = (createOrder.GoodsNum) * (_goodsRepository.GetById(createOrder.FromShopsId).NowPrice)
            };

            _ordersRepository.Insert(order);
            return new
            {
                Code = 1000,
                Data = order,
                Msg = "生成订单成功^_^"
            };
        }

    }
}